import cbor2
import os

# 1. 准备数据 - 明确将所有非hash_alg字段转换为bytes
data = {
    "quote": {
        "data": b"quote_test_value",          # 明确二进制数据
        "signature": b"quote_signature",      # 明确二进制数据
        "pcrs": {
            "hash_alg": "pcrs_hash_alg",      # 保留为文本字符串
            "values": {
                b"pcr0": b"pcr0_value",        # 明确二进制键和值
                b"pcr1": b"pcr1_value",        # 明确二进制键和值
                b"pcr2": b"pcr2_value",        # 明确二进制键和值
                b"pcr3": b"pcr3_value",        # 明确二进制键和值
                b"pcr4": b"pcr4_value",        # 明确二进制键和值
            }
        }
    },
    "ak_cert": b"uint8 ak_cert",              # 明确二进制数据
    "runtime_measurements": b"ima log"        # 明确二进制数据
}

# 2. 编码为CBOR
cbor_data = cbor2.dumps(data)

# 3. 写入文件
output_file = "data.cbor"
with open(output_file, "wb") as f:
    f.write(cbor_data)

# 4. 验证文件内容
print(f"CBOR数据已写入文件: {output_file}")
print("文件大小:", os.path.getsize(output_file), "字节")

# 5. 读取并验证类型
with open(output_file, "rb") as f:
    decoded = cbor2.load(f)
    
    # 验证所有字段类型
    assert isinstance(decoded["quote"]["data"], bytes), "quote.data 不是bytes类型"
    assert isinstance(decoded["quote"]["signature"], bytes), "quote.signature 不是bytes类型"
    assert isinstance(decoded["quote"]["pcrs"]["hash_alg"], str), "hash_alg 不是str类型"
    
    # 验证values中的键和值
    values = decoded["quote"]["pcrs"]["values"]
    assert isinstance(next(iter(values.keys())), bytes), "values键 不是bytes类型"
    assert isinstance(next(iter(values.values())), bytes), "values值 不是bytes类型"
    
    assert isinstance(decoded["ak_cert"], bytes), "ak_cert 不是bytes类型"
    assert isinstance(decoded["boot_measurements"], bytes), "boot_measurements 不是bytes类型"
    assert isinstance(decoded["runtime_measurements"], bytes), "runtime_measurements 不是bytes类型"

print("所有字段类型验证通过!")